#!/usr/bin/env python

import gobject

import dbus
import dbus.service
import dbus.mainloop.glib

import pygtrans

class DemoException(dbus.DBusException):
    _dbus_error_name = 'com.service.TranslateException'

class TranslatorObject(dbus.service.Object):
    
    @dbus.service.method("com.service.TranslateInterface",
                         in_signature='sss', out_signature='s')
    def get_trans(self, orig_txt, orig_lang, to_lang):
        
		#print orig_txt, orig_lang, to_lang
		
		if orig_txt == "" or to_lang == "":
			return ""
		
		if orig_lang == "":
			#Attempt to find language if original language is unspecified.
			orig_lang = pygtrans.get_text_lang(orig_txt)
		
		translation = pygtrans.translate(orig_txt, orig_lang, to_lang)
		
		return translation
    
    @dbus.service.method("com.service.TranslateInterface",
                         in_signature='s', out_signature='s')
    def get_lang(self, orig_txt):
        
		if orig_txt == "":
			return ""
		
		return pygtrans.get_text_lang(orig_txt)
    
    @dbus.service.method("com.service.TranslateInterface",
                         in_signature='', out_signature='')
    def Exit(self):
        mainloop.quit()

if __name__ == '__main__':
    #Loop has been changed to try and get more connectons at once.
    dbus_loop = dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    session_bus = dbus.SessionBus(mainloop=dbus_loop)
    
    name = dbus.service.BusName("com.service.Translate", session_bus)
    object = TranslatorObject(session_bus, '/TransObject')

    mainloop = gobject.MainLoop()
    print "Translate service running."
    mainloop.run()
    
